#include <stdlib.h>
#include <stdio.h>
#include <string.h>

typedef struct LinkNode
{
	int nVal;
	struct LinkNode * next;
} LinkNode;

LinkNode * GenerateLink(int nLen)
{
	LinkNode * pNext = NULL;
	while(nLen > 0)
	{
		LinkNode * pCurNode = (LinkNode *) malloc(sizeof(LinkNode));
		memset(pCurNode, 0, sizeof(LinkNode));

		pCurNode->nVal = nLen;
		pCurNode->next = pNext;
		pNext = pCurNode;
		nLen --;
	}
	return pNext;
}

void DestroyLink(LinkNode * pLink)
{
	LinkNode * pNext = pLink;
	while(pNext != NULL)
	{
		LinkNode * pCurNode = pNext;
		pNext = pCurNode->next;
		free(pCurNode);
	}
}

void RevertLink(LinkNode * * ppLink)
{
	LinkNode * pPrev = NULL;
	LinkNode * pNext = NULL;
	LinkNode * pCurNode = (* ppLink);
	while(pCurNode != NULL)
	{
		pNext = pCurNode->next;
		pCurNode->next = pPrev;
		pPrev = pCurNode;
		pCurNode = pNext;
	}
	(* ppLink) = pPrev;
}

void PrintLink(LinkNode * pLink)
{
	printf("Link:{");
	LinkNode * pNext = pLink;
	while(pNext != NULL)
	{
		printf("%03d,", pNext->nVal);
		pNext = pNext->next;
	}
	printf("}\n");
}

int main(int argc, char *argv[]) {
	printf("Link Practice\n");

	int nLen = 50;

	LinkNode * pLink = GenerateLink(nLen);
	PrintLink(pLink);
	RevertLink(&pLink);
	PrintLink(pLink);
	DestroyLink(pLink);

	return EXIT_SUCCESS;
}
